import React from 'react';
import { observer } from 'mobx-react';
import { WeaInput, WeaDialog, WeaSelect, WeaLocaleProvider } from 'ecCom';
import { SelectNew, Button } from 'antd';
import classNames from 'classnames';
import $ from 'jquery';
import ReactDOM from 'react-dom';
const getLabel = WeaLocaleProvider.getLabel;

@observer
export default class ExcelCellSelect extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            changing: false,
            type: 'field'
        }
    }

    render() {

        const {
            tableCellProps: { text, record, index, onEdit }
        } = this.props;
        const { fieldtype, showname, field, scrollTop } = record;
        const { options, value, tableCellProps } = this.props;
        const { type, changing } = this.state;
        const showSelect = (type === 'field' || !value) && !changing;
        return (
            <div className={classNames('edc-report-excel-cell-select', { changing })}>
                {changing && <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@66ffcr`} title={getLabel('516753', '单击文本框可返回字段赋值操作页面')} viewAttr={3} value={showname} readonly='readonly' onClick={(v, showname) => {
                    this.onChangeState();
                    setTimeout(() => {
                        $('.ant-table-body').scrollTop(scrollTop);
                    }, 50);
                    if (this.props.onChangeSize) {
                        this.props.onChangeSize('normal');
                    }
                }} />}
                {!changing && fieldtype != 'cellfield' && <div><WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@2yrx5i`}
                    options={options}
                    value={field}
                    viewAttr={3}
                    optionFilterProp='children'
                    showSearch={true}
                    onChange={(v, showname) => {
                        const { text, record, index, onEdit } = tableCellProps;
                        if (v) {
                            const [sheetName, fieldOrDetail, detailField] = v.split('.');
                            let newFieldtype;
                            if (detailField) {
                                newFieldtype = 'detailfield'
                            } else {
                                newFieldtype = 'mainfield'
                            }
                            onEdit({
                                type: "CUSTOM",
                                record: {
                                    ...record,
                                    showname: showname,
                                    fieldtype: newFieldtype,
                                    field: v
                                },
                                index,
                                key: "customrender",
                                value: 1
                            });
                        }
                    }}
                />
                    <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@qbp3qp`} title={getLabel('516752', '点击按钮到表格中选取单元格')} onClick={this.onSelectCell}><i className='icon-coms-release'> </i></Button></div>}

                {!changing && fieldtype == 'cellfield' && <div><WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@pmd8v5`} viewAttr={3} value={showname}
                    onChange={(v) => {
                        const { text, record, index, onEdit } = tableCellProps;
                        if (v) {
                            onEdit({
                                type: "CUSTOM",
                                record: {
                                    ...record,
                                    showname: v,
                                    fieldtype: 'cellfield',
                                    field: v
                                },
                                index,
                                key: "customrender",
                                value: 1
                            });
                        }
                    }}
                />
                    <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@sn69yi`} title={getLabel('516752', '点击按钮到表格中选取单元格')} onClick={this.onSelectCell}><i className='icon-coms-release'> </i></Button></div>}
            </div>
        )
    }

    componentDidUpdate() {
        if (this.state.changing) {
            //弹窗变小
            $(ReactDOM.findDOMNode(this)).closest('td').addClass('show-td');
        } else {
            //弹窗变大
            const td = $(ReactDOM.findDOMNode(this)).closest('td');
            if (td.hasClass('show-td')) {
                const allTd = td.parent().parent().find('tr>td:nth-child(2)>');
                allTd.find('.wea-select>div:first').removeClass('ant-select-focused');//选择框移除焦点
                td.parent().parent().find('tr').css('background-color', '');//行移除高亮样式
                td.find('.ant-input-wrapper').children("input:first").focus();//文本框设置焦点
                td.removeClass('show-td');
                td.find('.wea-select').children("div:first").addClass('ant-select-focused');//选择框设置焦点
                td.parent().css('background-color', '#EAF8FE');//行设置高亮样式
            }
        }
    }

    componentWillReceiveProps(nextProps) {
        if (!nextProps.value) {
            this.setState({ type: 'field' })
        }
    }

    onSelectCell = () => {
        const { tableCellProps } = this.props;
        const { text, record, index, onEdit } = tableCellProps;
        this.onChangeState();
        if (this.state.changing) {
            //弹窗变大
            const { scrollTop } = record;
            setTimeout(() => {
                $('.ant-table-body').scrollTop(scrollTop);
            }, 50);
            if (this.props.onChangeSize) {
                this.props.onChangeSize('normal', tableCellProps);
            }
        } else {
            //弹窗变小
            const scrollTop = $('.ant-table-body').scrollTop();
            //记录当前滚动条高度
            onEdit({
                type: 'CUSTOM',
                record: {
                    ...record,
                    scrollTop: scrollTop
                },
                index,
                key: 'customrender',
                value: 1
            });
            const { field, fieldtype } = record;
            if (this.props.onChangeSize) {
                this.props.onChangeSize('small', this);
            }
            if (this.props.setActiveCell) {
                this.props.setActiveCell(field, fieldtype);
            }
        }
    }

    onChangeState = () => {
        this.setState({
            type: 'cell',
            changing: !this.state.changing
        })
    }

    /**
    * 获取字段的行列索引
    */
    getFieldIndex = (fieldName) => {
        const [sheetName, fieldOrDetail, detailRow, detailField] = fieldName.split('.');
        let fieldIndex = {};
        if (sheetName) {
            var sheet = this.workbookInstance.getSheetFromName(sheetName);
            if (sheet && fieldOrDetail) {
                const tableName = fieldOrDetail.replace('_', '');
                const table = this.getDetailTable(`${sheetName}.${tableName}`);
                if (table) {
                    const bindingPath = table.bindingPath();
                    if (bindingPath) {
                        const { row, colCount, rowCount, col } = table.dataRange();
                        for (let i = 0; i < colCount; i++) {
                            const columnDataField = table.getColumnDataField(i);
                            if (columnDataField == detailField) {
                                if (detailRow)
                                    fieldIndex = { sheet: sheet, row: row + Number(detailRow), col: col + i };
                            }
                        }
                    }
                }
                if (!(detailRow && detailField)) {
                    const { data } = sheet.toJSON();
                    if (data) {
                        const { dataTable } = data;
                        if (dataTable) {
                            each(dataTable, (o, rowIndex) => {
                                each(o, (obj, colIndex) => {
                                    const bindingPath = sheet.getBindingPath(rowIndex, colIndex);
                                    if (bindingPath) {
                                        if (bindingPath == fieldName) {
                                            fieldIndex = { sheet: sheet, row: Number(rowIndex), col: Number(colIndex) };
                                        }
                                    }
                                });
                            });
                        }
                    }
                }
            }
        }
        return fieldIndex;
    }
}